/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.system.service.impl;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.DictCache;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.cache.SysCache;
import org.springblade.common.cache.UserCache;
import org.springblade.common.constant.BaseRoleConstant;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.TenantConstant;
import org.springblade.common.enums.DictEnum;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.sms.model.SmsCode;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.repair.entity.UserExt;
import org.springblade.modules.repair.entity.UserWeixin;
import org.springblade.modules.repair.service.IMaintainSignSetingService;
import org.springblade.modules.repair.service.IUserWeixinService;
import org.springblade.modules.repair.service.UserCertService;
import org.springblade.modules.repair.service.UserExtService;
import org.springblade.modules.repair.vo.DeptAddressListUserVO;
import org.springblade.modules.resource.builder.sms.SmsBuilder;
import org.springblade.modules.system.entity.*;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.mapper.TenantMapper;
import org.springblade.modules.system.mapper.UserMapper;
import org.springblade.modules.system.service.*;
import org.springblade.modules.system.vo.*;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

import static org.springblade.common.constant.CommonConstant.DEFAULT_PARAM_PASSWORD;
import static org.springblade.modules.resource.utils.SmsUtil.AUTH_CODE;


/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {
	private static final String GUEST_NAME = "guest";

	private final IUserDeptService userDeptService;
	private final IUserOauthService userOauthService;
	private final IRoleService roleService;
	private final BladeTenantProperties tenantProperties;
	private final IUserWeixinService userWeiXinService;
	@Lazy
	private final IDeptService deptService;
	private final IPostService postService;
	private final TenantMapper tenantMapper;
	private final IMaintainSignSetingService maintainSignSetingService;
	private final BladeRedis bladeRedis;
//	private final IMaintainGroupService maintainGroupService;
	private final UserExtService userExtService;
	private final UserCertService userCertService;

	/**
	 * 短信服务构建类
	 */
	private final SmsBuilder smsBuilder;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean submit(User user) {
		if (StringUtil.isBlank(user.getTenantId())) {
			user.setTenantId(BladeConstant.ADMIN_TENANT_ID);
		}
		String tenantId = user.getTenantId();
		Tenant tenant = SysCache.getTenant(tenantId);
		if (Func.isNotEmpty(tenant)) {
			Integer accountNumber = tenant.getAccountNumber();
			if (tenantProperties.getLicense()) {
				String licenseKey = tenant.getLicenseKey();
				String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
				accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
			}
			Integer tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId));
			if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
				throw new ServiceException("当前租户已到最大账号额度!");
			}
		}
		if (Func.isNotEmpty(user.getPassword())) {
			user.setPassword(DigestUtil.encrypt(user.getPassword()));
		}
		Integer userCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, user.getAccount()));
		if (userCount > 0 && Func.isEmpty(user.getId())) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		return save(user) && submitUserDept(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUser(User user) {
		String tenantId = user.getTenantId();
		Integer userCount = baseMapper.selectCount(
			Wrappers.<User>query().lambda()
				.eq(User::getTenantId, tenantId)
				.eq(User::getAccount, user.getAccount())
				.notIn(User::getId, user.getId())
		);
		if (userCount > 0) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
//		return updateUserInfo(user) && submitUserDept(user);
		return updateUserInfo(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUserInfo(User user) {

		// 关联用户关联表信息
		UserExt userExt = userExtService.getOne(Wrappers.<UserExt>lambdaQuery().eq(UserExt::getUserId,user.getId()));
		if(ObjectUtil.isEmpty(userExt)){
			userExt = new UserExt();
		}
		userExt.setUserId(user.getId());
		userExt.setAddress(user.getAddress());
		userExt.setLongitude(user.getLongitude());
		userExt.setLatitude(user.getLatitude());
		userExt.setVehicle(user.getVehicle());
		userExt.setShowInfo(user.getShowInfo());
		userExtService.saveOrUpdate(userExt);

		user.setPassword(null);
		return updateById(user);
	}

	private boolean submitUserDept(User user) {
		List<Long> deptIdList = Func.toLongList(user.getDeptId());
		List<UserDept> userDeptList = new ArrayList<>();
		deptIdList.forEach(deptId -> {
			UserDept userDept = new UserDept();
			userDept.setUserId(user.getId());
			userDept.setDeptId(deptId);
			userDeptList.add(userDept);
		});
		userDeptService.remove(Wrappers.<UserDept>update().lambda().eq(UserDept::getUserId, user.getId()));
		return userDeptService.saveBatch(userDeptList);
	}

	@Override
	public IPage<User> selectUserPage(IPage<User> page, User user, Long deptId, String tenantId) {
		List<Long> deptIdList = SysCache.getDeptChildIds(deptId);
		return page.setRecords(baseMapper.selectUserPage(page, user, deptIdList, tenantId));
	}

	@Override
	public IPage<UserVO> selectUserSearch(UserVO user, Query query) {
		LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>query().lambda();
		if (StringUtil.isNotBlank(user.getName())) {
			queryWrapper.like(User::getName, user.getName());
		}
		if (StringUtil.isNotBlank(user.getDeptName())) {
			String deptIds = SysCache.getDeptIdsByFuzzy(AuthUtil.getTenantId(), user.getDeptName());
			if (StringUtil.isNotBlank(deptIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(deptIds);
					ids.forEach(id -> wrapper.like(User::getDeptId, id).or());
				});
			}
		}
		if (StringUtil.isNotBlank(user.getPostName())) {
			String postIds = SysCache.getPostIdsByFuzzy(AuthUtil.getTenantId(), user.getPostName());
			if (StringUtil.isNotBlank(postIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(postIds);
					ids.forEach(id -> wrapper.like(User::getPostId, id).or());
				});
			}
		}
		IPage<User> pages = this.page(Condition.getPage(query), queryWrapper);
		return UserWrapper.build().pageVO(pages);
	}

	@Override
	public User userByAccount(String tenantId, String account) {
		return baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, account).eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED));
	}

	@Override
	public UserInfo userInfo(Long userId) {
		User user = baseMapper.selectById(userId);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(Long userId, UserEnum userEnum) {
		User user = baseMapper.selectById(userId);
		return buildUserInfo(user, userEnum);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, String password) {
		User user = baseMapper.getUser(tenantId, account, password);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String phone, UserEnum userEnum) {
		User user = baseMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User :: getTenantId, tenantId).eq(User :: getPhone, phone).eq(User :: getIsDeleted, 0));
		if (user == null) {
			throw new ServiceException("未找到相关账号!");
		}
		return buildUserInfo(user, userEnum);
	}

	@Override
	public UserInfo userInfo(String tenantId, String phone, String password, UserEnum userEnum) {
		User user = baseMapper.getUser(tenantId, phone, password);
		if (user == null || user.getId() == null) {
			throw new ServiceException("手机号码或密码不正确!");
		}
		return buildUserInfo(user, userEnum);
	}

	private UserInfo buildUserInfo(User user) {
		return buildUserInfo(user, UserEnum.WEB);
	}

	private UserInfo buildUserInfo(User user, UserEnum userEnum) {
		if (ObjectUtil.isEmpty(user)) {
			return null;
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setUser(user);
		userInfo.setStatus(user.getStatus());
		List<String> roleAlias = roleService.getRoleAliases(user.getRoleId());
		userInfo.setRoles(roleAlias);
		List<String> roleNames = roleService.getRoleNames(user.getRoleId());
		userInfo.setFullRoleNames(roleNames);
		List<String> deptNames = deptService.getDeptNamesByUserId(user.getId());
		userInfo.setDeptNames(deptNames);
		List<String> postNames = postService.getPostNames(user.getPostId());
		userInfo.setPostNames(postNames);
		Tenant tenant = tenantMapper.selectOne(Wrappers.<Tenant>query().lambda().eq(Tenant::getTenantId, user.getTenantId()));
		userInfo.setTenantName(tenant == null ? null : tenant.getTenantName());
//		int isSign = maintainSignSetingService.count(Wrappers.<MaintainSignSeting>lambdaQuery().eq(MaintainSignSeting :: getUserId, user.getId()).eq(MaintainSignSeting :: getIsDeleted, BladeConstant.DB_NOT_DELETED));
//		userInfo.setSign(isSign > 0 ? true : false);
		// 根据每个用户平台，建立对应的detail表，通过查询将结果集写入到detail字段
		Kv detail = Kv.create().set("type", userEnum.getName());
		if (userEnum == UserEnum.WEB) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else if (userEnum == UserEnum.APP) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		}
		userInfo.setDetail(detail);
		UserWeixin userWeixin = userWeiXinService.getOne(Wrappers.<UserWeixin>lambdaQuery().eq(UserWeixin::getUserId, userInfo.getUser().getId()));
		if (userWeixin != null) {
			userInfo.setOpenId(userWeixin.getOpenid());
		}
//		UserExt userExt = userExtService.getOne(Wrappers.<UserExt>lambdaQuery().eq(UserExt::getUserId,userInfo.getUser().getId()));
//		if(cn.hutool.core.util.ObjectUtil.isNotEmpty(userExt)){
//			MaintainGroup maintainGroup = maintainGroupService.getById(userExt.getMaintainGroupId());
//			if(cn.hutool.core.util.ObjectUtil.isNotEmpty(maintainGroup)){
//				userInfo.setMaintainGroupName(maintainGroup.getName());
//			}
//			userInfo.setGroupLeader(userExt.getGroupLeader());
//			userInfo.setMaintainGroupId(userExt.getMaintainGroupId());
//		}
		return userInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserInfo userInfo(UserOauth userOauth) {
		UserOauth uo = userOauthService.getOne(Wrappers.<UserOauth>query().lambda().eq(UserOauth::getUuid, userOauth.getUuid()).eq(UserOauth::getSource, userOauth.getSource()));
		UserInfo userInfo;
		if (Func.isNotEmpty(uo) && Func.isNotEmpty(uo.getUserId())) {
			userInfo = this.userInfo(uo.getUserId());
			userInfo.setOauthId(Func.toStr(uo.getId()));
		} else {
			userInfo = new UserInfo();
			if (Func.isEmpty(uo)) {
				userOauthService.save(userOauth);
				userInfo.setOauthId(Func.toStr(userOauth.getId()));
			} else {
				userInfo.setOauthId(Func.toStr(uo.getId()));
			}
			User user = new User();
			user.setAccount(userOauth.getUsername());
			user.setTenantId(userOauth.getTenantId());
			userInfo.setUser(user);
			userInfo.setRoles(Collections.singletonList(GUEST_NAME));
		}
		return userInfo;
	}

	@Override
	public boolean grant(String userIds, String roleIds) {
		User user = new User();
		user.setRoleId(roleIds);
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean resetPassword(String userIds) {
		User user = new User();
		user.setPassword(DigestUtil.encrypt(CommonConstant.DEFAULT_PASSWORD));
		user.setUpdateTime(DateUtil.now());
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
		User user = getById(userId);
		if (!newPassword.equals(newPassword1)) {
			throw new ServiceException("请输入正确的确认密码!");
		}
		if (!user.getPassword().equals(DigestUtil.hex(oldPassword))) {
			throw new ServiceException("原密码不正确!");
		}
		return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.hex(newPassword)).eq(User::getId, userId));
	}

	@Override
	public boolean removeUser(String userIds) {
		if (Func.contains(Func.toLongArray(userIds), AuthUtil.getUserId())) {
			throw new ServiceException("不能删除本账号!");
		}
		return deleteLogic(Func.toLongList(userIds));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void importUser(List<UserExcel> data, Boolean isCovered) {
		data.forEach(userExcel -> {
			User user = Objects.requireNonNull(BeanUtil.copy(userExcel, User.class));
			// 设置用户平台
			user.setUserType(Func.toInt(DictCache.getKey(DictEnum.USER_TYPE, userExcel.getUserTypeName()), 1));
			// 设置部门ID
			user.setDeptId(SysCache.getDeptIds(userExcel.getTenantId(), userExcel.getDeptName()));
			// 设置岗位ID
			user.setPostId(SysCache.getPostIds(userExcel.getTenantId(), userExcel.getPostName()));
			// 设置角色ID
			user.setRoleId(SysCache.getRoleIds(userExcel.getTenantId(), userExcel.getRoleName()));
			// 设置租户ID
			if (!AuthUtil.isAdministrator() || StringUtil.isBlank(user.getTenantId())) {
				user.setTenantId(AuthUtil.getTenantId());
			}
			// 覆盖数据
			if (isCovered) {
				// 查询用户是否存在
				User oldUser = UserCache.getUser(userExcel.getTenantId(), userExcel.getAccount());
				if (oldUser != null && oldUser.getId() != null) {
					user.setId(oldUser.getId());
					this.updateUser(user);
					return;
				}
			}
			// 获取默认密码配置
			String initPassword = ParamCache.getValue(DEFAULT_PARAM_PASSWORD);
			user.setPassword(initPassword);
			this.submit(user);
		});
	}

	@Override
	public List<UserExcel> exportUser(Wrapper<User> queryWrapper) {
		List<UserExcel> userList = baseMapper.exportUser(queryWrapper);
		userList.forEach(user -> {
			user.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
			user.setRoleName(StringUtil.join(SysCache.getRoleNames(user.getRoleId())));
			user.setDeptName(StringUtil.join(SysCache.getDeptNames(user.getDeptId())));
			user.setPostName(StringUtil.join(SysCache.getPostNames(user.getPostId())));
		});
		return userList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean registerGuest(User user, Long oauthId) {
		Tenant tenant = SysCache.getTenant(user.getTenantId());
		if (tenant == null || tenant.getId() == null) {
			throw new ServiceException("租户信息错误!");
		}
		UserOauth userOauth = userOauthService.getById(oauthId);
		if (userOauth == null || userOauth.getId() == null) {
			throw new ServiceException("第三方登陆信息错误!");
		}
		user.setRealName(user.getName());
		user.setAvatar(userOauth.getAvatar());
		user.setRoleId(StringPool.MINUS_ONE);
		user.setDeptId(StringPool.MINUS_ONE);
		user.setPostId(StringPool.MINUS_ONE);
		boolean userTemp = this.submit(user);
		userOauth.setUserId(user.getId());
		userOauth.setTenantId(user.getTenantId());
		boolean oauthTemp = userOauthService.updateById(userOauth);
		return (userTemp && oauthTemp);
	}

	@Override
	public boolean updatePlatform(Long userId, Integer userType, String userExt) {
		if (userType.equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userWeb.setId(query.getId());
			}
			userWeb.setUserId(userId);
			userWeb.setUserExt(userExt);
			return userWeb.insertOrUpdate();
		} else if (userType.equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userApp.setId(query.getId());
			}
			userApp.setUserId(userId);
			userApp.setUserExt(userExt);
			return userApp.insertOrUpdate();
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userOther.setId(query.getId());
			}
			userOther.setUserId(userId);
			userOther.setUserExt(userExt);
			return userOther.insertOrUpdate();
		}
	}

	@Override
	public UserVO platformDetail(User user) {
		User detail = baseMapper.selectOne(Condition.getQueryWrapper(user));
		UserVO userVO = UserWrapper.build().entityVO(detail);
		if (userVO.getUserType().equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else if (userVO.getUserType().equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		}
		return userVO;
	}

	@Override
	public String getUserRealNameAndCompanyName(User user) {
		String maintainCompanyName = this.baseMapper.getUserRealNameAndCompanyName(user.getId());
		return maintainCompanyName+":"+user.getRealName();
	}

	@Override
	public boolean checkPhone(String phone) {
		List<TenantInfoVO> userList = baseMapper.getTenantInfoByPhone(phone);
		if (ObjectUtil.isEmpty(userList)) {
			throw new ServiceException("您的手机号未加入，请联系贵司相关负责人添加!");
		}
		return true;
	}

	@Override
	public boolean captchaUpdatePassword(String phone, String code, String captchaId, String newPassword, String newPassword1) {
		User user = baseMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User :: getPhone, phone).eq(User :: getIsDeleted, 0));
		if (ObjectUtil.isEmpty(user)) {
			throw new ServiceException("用户不存在!");
		}

		SmsCode smsCode = new SmsCode();
		smsCode.setId(captchaId);
		smsCode.setValue(code);
		boolean validate = smsBuilder.template(AUTH_CODE, user.getTenantId()).validateMessage(smsCode);
		if (!validate) {
			throw new ServiceException("验证码错误!");
		}

		if (!newPassword.equals(newPassword1)) {
			throw new ServiceException("两次密码输入不一致!");
		}

		user.setPassword(DigestUtil.hex(newPassword));
		return baseMapper.updateById(user) > 0;
	}

	@Override
	public List<TenantInfoVO> getTenantInfoByPhone(String phone) {
		List<TenantInfoVO> tenantInfoList = baseMapper.getTenantInfoByPhone(phone);
		if (CollectionUtil.isEmpty(tenantInfoList)) {
			return tenantInfoList;
		}
		String uuid = IdUtil.randomUUID();
		bladeRedis.setEx(CommonConstant.LOGIN_KEY + phone, uuid, Duration.ofMinutes(5));
		for (TenantInfoVO tenantInfoVO : tenantInfoList) {
			tenantInfoVO.setVerificationKey(uuid);
		}
		return tenantInfoList;
	}

	@Override
	public UserInfo getuserGroupInfo(Long userId) {
		return baseMapper.getuserGroupInfo(userId);
	}

	@Override
	public List<SimpleUserVO> getUserByDeptAndRole(Long deptId, Long roleId) {
		return baseMapper.getUserByDeptAndRole(deptId, roleId);
	}

	@Override
	public ApproveUserVO getApproveUser(Long submitId) {
		Set<SimpleUserVO> groupLeaders = new LinkedHashSet<>();
		Set<SimpleUserVO> managerNames = new LinkedHashSet<>();

		String tenantId = AuthUtil.getTenantId();
		// 组长角色
		Long groupRoleId = roleService.getRoleIdByAliases(tenantId, BaseRoleConstant.MAINTENANCE_GROUP_LEADER);
		// 经理角色
		Long managerRoleId = roleService.getRoleIdByAliases(tenantId, BaseRoleConstant.MAINTENANCE_MANAGER);

		// 标记已查找的部门
		List<Long> deptFlag = new ArrayList<>();
		// 提交人所在部门祖级列表
		List<String> deptAncestors = deptService.getAncestorsByUserIds(submitId);
		for (String deptAncestor : deptAncestors) {
			List<Long> deptIds = Func.toLongList(deptAncestor);
			// 提交者所在部门
			Long curDeptId = deptIds.get(deptIds.size() - 1);
			// 所在组“组长”角色用户集合
			List<SimpleUserVO> groupUsers = this.getUserByDeptAndRole(curDeptId, groupRoleId);
			if (Func.isNotEmpty(groupUsers)) {
				groupLeaders.addAll(groupUsers);
			}

			// 从所在部门依次往上寻找“经理”角色用户集合
			for (int i = deptIds.size() - 1 ; i > 0; i--) {
				if (deptFlag.contains(deptIds.get(i))) {
					continue;
				}
				deptFlag.add(deptIds.get(i));
				List<SimpleUserVO> managerUsers = this.getUserByDeptAndRole(deptIds.get(i), managerRoleId);
				if (Func.isNotEmpty(managerUsers)) {
					managerNames.addAll(managerUsers);
					break;
				}
			}
		}

		/**
		 * 若找不到维保经理，则取管理员
		 * 若找不到维保组长，则取维保经理
		 */
		if (Func.isEmpty(managerNames)) {
			// 管理员角色
			Long adminRoleId = roleService.getRoleIdByAliases(tenantId, RoleConstant.ADMIN);
			List<SimpleUserVO> adminUsers = this.getUserByDeptAndRole(null, adminRoleId);
			managerNames.addAll(adminUsers);
		}
		if (Func.isEmpty(groupLeaders)) {
			groupLeaders.addAll(managerNames);
		}

		// 数据封装
		ApproveUserVO approveUserVO = new ApproveUserVO();
		approveUserVO.setGroupUsers(groupLeaders);
		approveUserVO.setManagerUsers(managerNames);

		return approveUserVO;
	}

	@Override
	public ApproveUserDataVO getApproveUserData(Long submitId) {
		ApproveUserVO approveUser = this.getApproveUser(submitId);
		String groupApproveIds = approveUser.getGroupUsers().stream().map(t -> String.valueOf(t.getUserId())).collect(Collectors.joining(","));
		String groupApproveNames = approveUser.getGroupUsers().stream().map(t -> t.getUserName()).collect(Collectors.joining(","));

		Set<SimpleUserVO> mergeUsers = new LinkedHashSet<>();
		mergeUsers.addAll(approveUser.getGroupUsers());
		mergeUsers.addAll(approveUser.getManagerUsers());
		String approveIds = mergeUsers.stream().map(t -> String.valueOf(t.getUserId())).collect(Collectors.joining(","));
		String approveNames = mergeUsers.stream().map(t -> t.getUserName()).collect(Collectors.joining(","));

		ApproveUserDataVO approveUserDataVO = new ApproveUserDataVO();
		approveUserDataVO.setGroupApproveIds(groupApproveIds);
		approveUserDataVO.setGroupApproveNames(groupApproveNames);
		approveUserDataVO.setApproveIds(approveIds);
		approveUserDataVO.setApproveNames(approveNames);
		return approveUserDataVO;
	}

	@Override
	public SimpleUserVO getSimpleUserInfo(Long userId) {
		return baseMapper.getSimpleUserInfo(userId);
	}

	@Override
	public String getOpenIdByPhone(String phone) {
		return baseMapper.getOpenIdByPhone(phone);
	}

	@Override
	public List<Long> getUserByRoleName(String roleName) {
		String tenantId = AuthUtil.getTenantId();
		Long roleId = roleService.getRoleIdByAliases(tenantId, roleName);
		List<Long> userIds = baseMapper.getUserByRoleId(tenantId, roleId);

		// 若找不到对应用户，admin角色兜底
		if (Func.isEmpty(userIds)) {
			// 管理员角色
			Long adminRoleId = roleService.getRoleIdByAliases(tenantId, RoleConstant.ADMIN);
			userIds = baseMapper.getUserIdByDeptAndRole(null, adminRoleId);
		}

		return userIds;
	}

	@Override
	public List<Long> getUserByOwnDeptParent(Long applyUserId, String roleNames) {
		List<Long> userIds = new ArrayList<>();
		String tenantId = AuthUtil.getTenantId();
		List<String> roleNameList = Func.toStrList(roleNames);
		// 标记 最后一个角色才开始逐级往上找
		int sizeFlag = roleNameList.size();
		for (String roleName : roleNameList) {
			Long roleId = roleService.getRoleIdByAliases(tenantId, roleName);
			// 提交人所在部门祖级列表
			List<String> deptAncestors = deptService.getAncestorsByUserIds(applyUserId);
			for (String deptAncestor : deptAncestors) {
				List<Long> deptIds = Func.toLongList(deptAncestor);
				// 提交者所在部门
				Long curDeptId = deptIds.get(deptIds.size() - 1);
				// 所在组角色用户集合
				List<Long> firstUsers = baseMapper.getUserIdByDeptAndRole(curDeptId, roleId);
				if (Func.isNotEmpty(firstUsers)) {
					userIds.addAll(firstUsers);
					break;
				} else {
					if (--sizeFlag == 0) {
						// 从所在部门依次往上寻找角色用户集合
						for (int i = deptIds.size() - 1 ; i > 0; i--) {
							List<Long> otherUsers = baseMapper.getUserIdByDeptAndRole(deptIds.get(i), roleId);
							if (Func.isNotEmpty(otherUsers)) {
								userIds.addAll(otherUsers);
								break;
							}
						}
					}
				}
			}

			if (Func.isNotEmpty(userIds)) {
				break;
			}
		}

		/**
		 * 若找不到对应用户，admin角色兜底
		 */
		if (Func.isEmpty(userIds)) {
			// 管理员角色
			Long adminRoleId = roleService.getRoleIdByAliases(tenantId, RoleConstant.ADMIN);
			List<Long> adminUsers = baseMapper.getUserIdByDeptAndRole(null, adminRoleId);
			userIds.addAll(adminUsers);
		}

		return userIds;
	}

	@Override
	public List<UserVO> getUserList(List<Long> userIds) {
		return baseMapper.getUserList(userIds);
	}

	@Override
	public List<Long> listUserByDeptIds(List<Long> userDeptList) {
		return baseMapper.listUserByDeptIds(userDeptList);
	}

	@Override
	public Integer countUserSubscribe(List<Long> deptIds) {
		return baseMapper.countUserSubscribe(deptIds);
	}

	@Override
	public List<DeptAddressListUserVO> selectDeptUser(Long deptId) {
		return baseMapper.selectDeptUser(deptId);
	}

	@Override
	public Integer countUserByDept(List<Long> deptIds) {
		return baseMapper.countUserByDept(deptIds);
	}

	@Override
	public List<SimpleUserVO> getSimpleUserInfoByElevatorUseType(Long elevatorId, Integer useType) {
		return baseMapper.getSimpleUserInfoByElevatorUseType(elevatorId,useType);
	}

	@Override
	public List<SimpleUserVO> getAdminInfoByTenant(String tenantId) {
		return baseMapper.getAdminInfoByTenant(tenantId);
	}

	@Override
	public List<String> getDeptNames(Long userId) {
		return baseMapper.getDeptNames(userId);
	}

	@Override
	public SimpleUserVO getSimpleEstateUserByPhone(String phone) {
		return baseMapper.getSimpleEstateUserByPhone(phone);
	}

	@Override
	public String getEstateOpenIdByPhone(String phone) {
		return baseMapper.getEstateOpenIdByPhone(phone);
	}

	@Override
	public List<SimpleUserVO> selectElevatorSubUser(Long elevatorId) {
		return baseMapper.selectElevatorSubUser(elevatorId);
	}

	@Override
	public List<Role> getRoleByUserId(Long userId) {
		return baseMapper.getRoleByUserId(userId);
	}

    @Override
    public List<User> getUserListOfRoleCode(String roleCode,String tenantId) {
        return baseMapper.getUserListOfRoleCode(roleCode,tenantId);
    }

    @Override
    public String getUserAppPushId(Long userId) {
		return baseMapper.getUserAppPushId(userId);
    }

	@Override
	public List<SimpleUserVO> listUserSimpleInfo(List<Long> userIds) {
		return baseMapper.listUserSimpleInfo(userIds);
	}



	@Override
	public List<SimpleUserVO> getUserByDeptIdsAndRoleAlias(String deptIds, String roleAlias) {
		if (Func.isEmpty(deptIds)) {
			return new ArrayList<>();
		}
		return baseMapper.getUserByDeptIdsAndRoleAlias(deptIds.replace(",","|"), roleAlias);
	}

	@Override
	public List<SimpleUserVO> getUserByRoleAlias(String roleAlias, String tenantId) {
		return baseMapper.getUserByRoleAlias(roleAlias, tenantId);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updatePasswordByPhone(String phone, String newPassword) {
		// 获取当前用户
		List<User> existUserList = this.list(Wrappers.<User>lambdaQuery().eq(User::getPhone, phone));
		if(Func.isEmpty(existUserList)){
			throw new ServiceException("手机号码还未加入通讯录，无法修改密码 \n 请联系公司负责人在通讯录添加您的信息");
		}
		existUserList = existUserList.stream().filter(u -> !Integer.valueOf(2).equals(u.getStatus()))
			.collect(Collectors.toList());

		// 密码加密，批量更新
		List<User> userList = existUserList.stream().peek(u -> u.setPassword(DigestUtil.hex(newPassword)))
			.collect(Collectors.toList());
		return this.saveOrUpdateBatch(userList);
	}

	@Override
	public List<AppUserTenantInfoVO> getAppUserTenantInfoByPhone(String phone) {
		List<AppUserTenantInfoVO> userInfoList = baseMapper.getAppUserTenantInfoByPhone(phone);
		if(CollectionUtil.isEmpty(userInfoList)){
			return new ArrayList<>();
		}
		userInfoList.forEach(u -> u.setIsPasswordSet(Func.isNotBlank(u.getPassword())));
		return userInfoList;
	}

	@Override
	@TenantIgnore
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateUserAllPassword(List<AppUserTenantInfoVO> appTenantInfoByPhone, String newPassword) {
		String password = DigestUtil.hex(newPassword);
		List<Long> userIds = appTenantInfoByPhone.stream().map(AppUserTenantInfoVO::getUserId).collect(Collectors.toList());
		List<User> userList = this.list(new LambdaQueryWrapper<User>().in(User::getId, userIds));
		userList.forEach(u -> u.setPassword(password));
		return this.updateBatchById(userList);
	}

	@Override
	public List<AppUserTenantInfoVO> getAppUserTenantInfoByPhoneAndPassword(String phone, String password) {
		List<AppUserTenantInfoVO> userInfoList = baseMapper.getAppUserTenantInfoByPhoneAndPassword(phone,password);
		if(CollectionUtil.isEmpty(userInfoList)){
			return new ArrayList<>();
		}
		userInfoList.forEach(u -> u.setIsPasswordSet(Func.isNotBlank(u.getPassword())));
		return userInfoList;
	}
}
